<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="box">
        <div id="firBox">
            <input type="text" id="inp"><br>
            <button id="btn">click button</button>
        </div>

        <div><!-- 数据驱动视图部分 --></div>
        
    </div>
    <script>
        // 1、选择排序
        const arr = [3, 4, 2, 5, 1, 6, 8, 7, 9]

            ~ function () {
                let temp
                for (let p = 0; p <= arr.length - 2; p++) {
                    let smallest = arr[p]
                    let smallestIndex = p
                    for (let i = p; i <= arr.length; i++) {
                        // if (arr[i] < smallest) {
                        // arr[smallestIndex] === smallest
                        if (arr[i] < arr[smallestIndex]) {
                            smallest = arr[i]
                            smallestIndex = i
                        }
                    }
                    temp = arr[p]
                    arr[p] = smallest
                    arr[smallestIndex] = temp
                }
                console.log("选择排序", arr);
            }()
            // //冒泡排序
            ~ function () {
                let temp
                for (let j = arr.length - 2; j >= 0; j--) {
                    for (let i = 0; i <= j; i++) {
                        if (arr[i] > arr[i + 1]) {
                            temp = arr[i]
                            arr[i] = arr[i + 1]
                            arr[i + 1] = temp
                        }
                    }
                }
                console.log("冒泡排序:", arr);
            }()

        // 2、深拷贝
        function deepCopy(data) {
            //基本数据类型   //函数
            if (typeof data !== "function" && typeof data !== "object" || typeof data === "function") {
                return data
            } else if (Array.isArray(data)) {
                let arrCopy = []
                data.forEach(
                    (item, index) => {
                        // console.log(item);
                        // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!");
                        // console.log(index);
                        // console.log("++++++++++++++++++");
                        arrCopy[index] = deepCopy(item)


                    }
                )
                return arrCopy
            }
            //对象
            let objCopy = {}
            // key 键 
            for (let key in data) {
                console.log(key)
                let value = data[key]

                objCopy[key] = deepCopy(value)
            }
            return objCopy
        }
        let obj = {
            names: "小青",
            ages: 48,
            sex: "男"
        }
        let ffn = deepCopy(obj)
        // let ffn = fn(obj)
        console.log("++++++拷贝，且不改变初始值 ， 少女 ++++++");
        ffn.sex = "女"
        ffn.ages = 18
        console.log(ffn.sex);
        console.log(ffn.ages);
        console.log(ffn);
        console.log("+++++++初始值内容 ， 油腻男+++++");
        console.log(obj.sex);
        console.log(obj.ages);
        console.log(obj)



        // //3、手撸函数防抖与节流

        // //防抖
        let thePval_01 = document.createElement("p");
        firBox.appendChild(thePval_01)
        const inputHandler = function (e) {
            console.log(e.target);
            // console.log(e.target.value);
            thePval_01.innerText = e.target.value
        }
        inp.addEventListener('input', mydebounce(inputHandler, 1000))

        function mydebounce(fn, delay) {
            let timer = null
            return function (...args) {
                if (timer) {
                    clearTimeout(timer)
                }
                timer = setTimeout(() => {
                    fn.apply(null, args)
                    timer = null
                }, delay)
            }
        }

        // 节流
        let thePval_02 = document.createElement("span");
        firBox.appendChild(thePval_02)
        let clickNum = 0
        let ilay

        function formatDuring(mss) {
            var seconds = (mss % (1000 * 60)) / 1000;
            return seconds + " 秒 ";
        }
        const clickHandler = function (e) {
            // console.log('hello');
            clickNum += 1
            thePval_02.innerText = `节流时效为 ${formatDuring(ilay)} , 点击生效的次数为 => ( ${clickNum} )`
        }
        btn.addEventListener('click', mythrottle(clickHandler, 2000))

        function mythrottle(fn, delay) {
            ilay = delay
            let timer = null
            return function (...args) {
                if (!timer) {
                    fn.apply(null, args)
                    timer = setTimeout(() => {
                        timer = null
                    }, delay)
                }
            }
        }

        // 4、使用连环异步回调实现求5的阶乘：
        ! function () {
            const multiply = (a, b, callback) => {
                setTimeout(() => callback(a * b), 1000);
            };
            const mulPromise = (a, b) => {
                return new Promise(
                    (resolve, reject) => {
                        multiply(a, b, (ret) => resolve(ret));
                    }
                );
            };
            mulPromise(2, 3)
                .then((ret) => mulPromise(ret, 4))
                .then((ret) => mulPromise(ret, 5))
                .then((ret) => console.log("ret=", ret));

            ~(async function awaitDemo() {
                try {
                    let ret = await mulPromise(2, 3);
                    ret = await mulPromise(ret, 4);
                    ret = await mulPromise(ret, 5);
                    console.log(ret);
                } catch (err) {
                    console.log("err=", err);
                }
            })();
        }()

        // 5、提取URL中的查询参数
        function getSearchParams(url = "") {
            const obj = {};
            url.match(/\w+=\w+/g).forEach((item) => {
                let [key, value] = item.split("=");
                obj[key] = value
            });
            return obj;
        }
        var url = "http://baidu.com?name=12&ages=18#abc"
        const myurl = getSearchParams(url)
        console.log("提取url的值:", myurl)



            // // 6、封装ajax,实现POST一个表单
            ~ function () {
                function getSearchParams(url = '') {
                    const obj = {}
                    url.match(/\w+=\w+/g).forEach(str => {
                        let [key, value] = str.split('=')
                        obj[key] = value
                    })
                    return obj
                }
                // var url = "http://www.baidu.com?name=12&ages=18#abc"
                // // console.log(myurl)
                // // 这个myurl与上面那个myurl无关，因为不在同一个作用域的常量，只要不在当前作用域的上方进行调用就没问题
                // const myurl = getSearchParams(url)
                // console.log(myurl)
                obj = {
                    name: 'heige',
                    age: 12
                }

                function toGetParams(obj) {
                    let str = ''
                    for (let key in obj) {
                        str += `&${key}=${obj[key]}`
                    }
                    return str.slice(1)
                }

                function ajax({
                    url,
                    method,
                    data,
                    dataType,
                    onSuccess,
                    onFail
                }) {
                    const xhr = new XMLHttpRequest()
                    if (!url) {
                        throw new Error('没给url')
                    }
                    method = method || 'GET'
                    onSuccess = onSuccess || (data => console.log('default onSuccess:', data))
                    onFail = onFail || (err => console.log('default onFail:', err))
                    xhr.open(method, url)
                    let reqBody = null
                    switch (true) {
                        case dataType == 'form':
                            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
                            reqBody = toGetParams(data)
                            break
                        case dataType == 'json':
                            xhr.setRequestHeader('Content-Type', 'application/json')
                            reqBody = JSON.stringify(data)
                            break
                        default:
                            break
                    }
                    xhr.onload = () => onSuccess(xhr.responseText)
                    xhr.onerror = err => onFail(err)
                    xhr.send(reqBody)
                }
                // try {
                //   ajax({
                //     url: 'http://www.httpbin.org/post',
                //     method: 'POST',
                //     dataType: 'form',
                //     data: { name: 'admin', pwd: '123456' },
                //     onSuccess: data => console.log(data),
                //     onFail: err => console.log(err)
                //   })
                // } catch (err) {
                //   console.log('catch err:', err);
                // }
                function ajaxPromise(config) {
                    return new Promise((resolve, reject) => {
                        ajax({
                            ...config,
                            onSuccess: data => resolve(data),
                            onFail: err => reject(err),
                        })
                    })
                }
                ajaxPromise({
                        url: 'http://www.httpbin.org/post',
                        method: 'POST',
                        dataType: 'form',
                        data: {
                            name: 'admin',
                            pwd: '123456'
                        },
                    })
                    .then(data => console.log(data))
                    .catch(err => console.log(err))
            }()



            // 7、带有超时功能的Promise
            ~ function () {
                function fn() {
                    let resoTim = 5000
                    let rejTim = 3000
                    async function executeWithTimeout(fn, ms) {
                        return new Promise(async (resolve, reject) => {
                            let timer = setTimeout(() => {
                                reject("timeout , 午时已到！拔枪~!");
                            }, ms);
                            const data = await fn();
                            clearTimeout(timer);
                            resolve(data);
                        });
                    }
                    const timeout = rejTim;

                    function rq(url) {
                        return new Promise((resolve) => {
                            setTimeout(() => {
                                resolve(`来自${url}的数据`);
                            }, timeout);
                        });
                    }
                    async function fn1() {
                        return rq("https://www.taobao.com");
                    }

                    executeWithTimeout(fn1, resoTim)
                        .then((value) => {
                            console.log("带有超时功能的Promise , value=", value)
                        })
                        .catch((err) => console.log("err=", err));
                }
                fn()
            }()

        // 8、一次性获取多个指定页面
        !function () {
            function fn3() {
                async function getContentByUrl(url) {
                    return new Promise((resolve, reject) =>
                        setTimeout(() => {
                            Math.random() > 0.5 ? resolve(`${url}的页面内容`) : reject("timeout");
                        }, 1000)
                    );
                }
                const urls = [
                    "https://www.taobao.com",
                    "https://www.baidu.com",
                    "https://web.taobao.com",
                ];

                async function fetchData(urls = []) {
                    return Promise.allSettled(
                        urls
                        .filter((url) => url.endsWith("taobao.com"))
                        .map((url) => getContentByUrl(url))
                    );
                }

                fetchData(urls)
                    .then((results) => console.log(results));
            }
            fn3()
        }()

        // 9、IP地址比大小
        ! function () {
            function fn1() {
                function compare(ip1 = "", ip2 = "") {
                    const arr1 = ip1.split(".").map((item) => item * 1);
                    const arr2 = ip2.split(".").map((item) => item * 1);
                    for (let i = 0; i < arr1.length; i++) {
                        if (arr1[i] > arr2[i]) {
                            return 1;
                        }
                        if (arr1[i] < arr2[i]) {
                            return -1;
                        }
                    }
                    return 0;
                }
                console.log(compare("1.2.3.4", "1.1.3.4"));
                console.log(compare("1.11.3.4", "1.2.3.4"));
                console.log(compare("1.2.3.4", "1.11.3.4"));
                console.log(compare("1.2.3.4", "1.2.3.4"));
            }
            fn1()
        }()

        // 10、实现闭包管理全班学生成绩
        ~ function () {
            let secBox = document.createElement("div")
            let myIp = document.createElement("input")
            let btnSet = document.createElement("button")
            let btnGet = document.createElement("button")
            let pInfo = document.createElement("p")
            box.appendChild(secBox)
            secBox.appendChild(myIp)
            secBox.appendChild(btnSet)
            secBox.appendChild(btnGet)
            secBox.appendChild(pInfo)
            myIp.type = "text"
            btnSet.innerText = "设置成绩"
            btnGet.innerText = "查询成绩"
            pInfo.innerText = "成绩显示区"
            myIp.placeholder = "请输入要查询的学生姓名"

            function scrore(name) {
                const scores = {
                    chinese: 0,
                    math: 0,
                    coding: 0,
                };

                return {
                    set(key, value) {
                        scores[key] = value;
                        console.log()
                    },
                    // zf(){
                    //     scores.coding+=
                    // }
                    // ,
                    getAll() {
                        return `${name}:${JSON.stringify(scores)}`;
                    },
                };
                console.log(scores)
            }
            const arr1 = ["张三疯", "尼古拉斯赵四", "隔壁老王"]
            const obj = {}
            arr1.forEach(
                name => obj[name] = scrore(name)
            )
            btnSet.onclick = function () {
                // 拿到用户的输入 张三疯:chinese:50
                let [name, key, value] = myIp.value.split(":")

                // 调用name对应的闭包中的set设置该生的科目成绩
                obj[name].set(key, value)
            }
            /*
            <input type="text" placeholder="请输入要查询的学生姓名" id="myIp" />
            <button id="btnSet">设置成绩</button>
            <button id="btnGet">查询成绩</button>
            <p id="pInfo">成绩显示区</p>
        */

            /* 根据姓名查询学生的全部成绩 */
            btnGet.onclick = function () {
                const name = myIp.value
                // 根据名字拿到其成绩闭包的操作API 进而调用getAll
                pInfo.innerText = obj[name].getAll()
            }
        }()

        // 11、手封MyMap实现一下效果
        ! function () {
            class MyMap {
                constructor() {
                    this.obj = {};
                    this.size = 0;
                }

                set(key, value) {
                    this.obj[key] = value;
                    this.updateSize();
                }

                get(key) {
                    return this.obj[key];
                }

                updateSize() {
                    this.size = Object.keys(this.obj).length;
                }

                delete(key) {
                    delete this.obj[key];
                    this.updateSize();
                }

                clear() {
                    this.obj = {};
                    this.size = 0;
                }

                has(key) {
                    return this.obj.hasOwnProperty(key);
                }

                forEach(handler) {
                    for (let key in this.obj) {
                        handler.apply(this, [this.obj[key], key, this]);
                    }
                }

                keys() {
                    return Object.keys(this.obj);
                }

                values() {
                    return Object.keys(this.obj).map((key) => this.obj[key]);
                }

                entries() {
                    return Object.keys(this.obj).map(
                        (key) => ({
                            key,
                            value: this.obj[key]
                        })
                    );
                }
            }~(function () {
                const map = new MyMap()
                map.set("name", "小三")
                map.set("age", 24)
                map.set("gender", "男")

                map.forEach(
                    (value, key) => console.log(key, value)
                )

                for (let entry of map.entries()) {
                    console.log(entry)
                }

                console.log(map.size)
                console.log(map.get("name"))
                console.log(map.get("age"))

                console.log(map.has("name"))
                console.log(map.has("myname"))

                map.delete("age")
                map.clear()
                console.log(map.size)
            })()

        }()

        // 12、全班人马排除空座位后抽取N名幸运观众
        ~ function () {
            function fn3() {
                let stus = [];
                for (let i = 1; i < 100; i++) {
                    stus.push(i);
                }
                const empties = [12, 34, 56, 78];
                stus = stus.filter((s) => empties.indexOf(s) === -1);
                const pick = (arr, n) => {
                    let luckies = [];
                    for (let i = 0; i < n; i++) {
                        let randomIndex = parseInt(Math.random() * arr.length);
                        luckies = arr.splice(randomIndex, 1).concat(luckies)
                    }

                    return luckies;
                };
                console.log(pick(stus, 5));
            }
            fn3();
        }()

        // 13、手撸观察者模式：实现彩票机周期性地发布【开售】【开奖】事件，玩家开售时下注，开奖时购买，一旦中奖则彩票机停止工作；
        ! function () {
            function observerDemo() {
                class Observable {
                    constructor(name) {
                        this.name = name;
                        this.observers = [];
                    }
                    register(ob) {
                        this.observers.push(ob);
                        ob.observable = this;
                    }
                    unregister(ob) {
                        this.observers = this.observers.filter((o) => o !== ob);
                    }
                    emit(event) {
                        this.observers.forEach((ob) => ob.onEvent(event));
                    }
                }
                class Observer {
                    constructor(name) {
                        this.name = name;
                    }
                    onEvent(event) {
                        console.log(this.name, "响应事件", event);
                    }
                }
                class Lottery extends Observable {
                    constructor(name) {
                        super(name);
                        this.timer = null;
                    }
                    start() {
                        if (!this.timer) {
                            this.timer = setInterval(() => {
                                const code = parseInt(Math.random() * 3);
                                console.log(this.name, "发布开奖事件", code);
                                this.emit({
                                    type: "开奖",
                                    code
                                });
                                this.emit({
                                    type: "开售"
                                });
                            }, 2000);
                        }
                    }
                    stop() {
                        if (this.timer) {
                            clearInterval(this.timer);
                            console.log(this.name, "已停止");
                            this.timer = null;
                        }
                    }
                }
                class Player extends Observer {
                    constructor(name) {
                        super(name);
                        this.code = null;
                    }
                    buy() {
                        this.code = parseInt(Math.random() * 3);
                        console.log(this.name, "下注", this.code);
                    }
                    check(event) {
                        const isLucky = this.code === event.code;
                        console.log(this.name, isLucky ? "中奖了" : "未中奖");
                        isLucky && this.observable.stop();
                    }
                    onEvent(event) {
                        super.onEvent(event);
                        switch (event.type) {
                            case "开售":
                                this.buy();
                                break;
                            case "开奖":
                                this.check(event);
                                break;

                            default:
                                break;
                        }
                        console.log("");
                    }
                }

                ~(function main() {
                    const lot = new Lottery("六合彩");
                    const tiger = new Player("今晚打老虎");
                    const chDao = new Player("陈刀仔");

                    lot.register(tiger);
                    lot.register(chDao);

                    // 禁止参赛的选手
                    // lot.unregister(chDao);

                    lot.start();
                })();
            }
            observerDemo();
        }()


        // 14、实现任意多个入参的函数fn的柯里化
        function fn5() {
            const curry = (fn) => {
                return function cfn(...args) {
                    if (args.length === fn.length) {
                        return fn(...args);
                    }
                    return function (...b) {
                        args = args.concat(b);
                        return cfn(...args);
                    };
                };
            };
            const add = (a, b, c, d) => a + b + c + d;
            const cadd = curry(add);
            console.log(cadd(12, 21, 32, 41));
            console.log(cadd(23)(21)(32)(41));
            console.log(cadd(1, 2)(3)(4));
        }
        fn5()


        // 15、实现任意多个函数的管道与组合
        function fn6() {
            /* 管道 */
            const pipe =
                (...fns) =>
                (v) =>
                fns.reduce((pv, fn) => fn(pv), v);
            const compose =
                (...fns) =>
                (v) =>
                fns.reverse().reduce((pv, fn) => fn(pv), v);
            const len = (n) => {
                console.log("len", n);
                return (n + "").length;
            };
            const pow = (n) => {
                console.log("pow", n);
                return n * n;
            };
            const cubicRoot = (n) => {
                console.log("cubicRoot", n);
                return Math.cbrt(n)
            };
            // 从左往右处理
            // console.log(pipe(len, pow, cubicRoot)(10));
            // 从右往左处理
            console.log(compose(len, pow, cubicRoot)(1000));
        }
        fn6()


        // 16、函数的Promise化
        async function promDemo() {
            function promisify(fn) {
                return function (...args) {
                    return new Promise(
                        (resolve, reject) => {
                            try {
                                resolve(fn.apply(null, args))
                            } catch (err) {
                                reject(err)
                            }
                        }
                    )
                }
            }

            const add = (a, b, c, d) => {
                if (Math.random() > 0.7) {
                    throw new Error("人品槽已空，请尽快充100块钱的人品")
                }
                return a + b + c + d
            }
            const pow = (a, b) => {
                if (Math.random() > 0.7) {
                    throw new Error("人品槽已空，请尽快充100块钱的人品")
                }
                return Math.pow(a, b)
            }

            const padd = promisify(add)
            const ppow = promisify(pow)

            // padd(1,2,3,4).then(
            //     data => {
            //         console.log("data=",data)
            //         return ppow(data,2)
            //     }
            // )
            // .then(
            //     data => console.log("data=",data)
            // )
            // .catch(
            //     err => console.error("err=",err)
            // )

            try {
                let data = await padd(1, 2, 3, 4)
                console.log("data=", data)

                data = await ppow(data, 2)
                console.log("data=", data)
            } catch (err) {
                console.error("err=", err)
            }

        }
        promDemo()


        // 17、封装MongoDB数据引擎层 
        async function fn3() {
            function getCollection(dbName, collectionName) {
                return new Promise(
                    (resolve, reject) => {
                        var MongoClient = require("mongodb").MongoClient;
                        var url = "mongodb://localhost:27017/";

                        MongoClient.connect(url, function (err, conn) {
                            if (err) {
                                resolve({
                                    err,
                                    collection: undefined,
                                    conn: undefined,
                                });
                                return;
                            }

                            var dbo = conn.db(dbName);
                            const collection = dbo.collection(collectionName);
                            resolve({
                                err: undefined,
                                collection,
                                conn,
                            });
                        });
                    }
                );
            }

            async function doCreate(dbName, collectionName, dataObj) {
                const {
                    err,
                    collection,
                    conn
                } = await getCollection(
                    dbName,
                    collectionName
                );
                if (err) {
                    return {
                        err,
                        res: undefined,
                    };
                }

                collection.insertOne(dataObj, function (err, res) {
                    conn.close();
                    return {
                        err,
                        res,
                    };
                });
            }
            async function addUser(user) {
                const ret = await doCreate(dbName, collectionName, user);
                return ret;
            }
        }
        fn3();

        //18、异步函数的Promise化 
        function fn8() {
            function add(a, b) {
                return a + b;
            }

            function multiply(a, b, callback) {
                setTimeout(() => callback(a * b), 1000);
            }

            function promisify(fn) {
                return function pfn(...args) {
                    return new Promise(
                        (resolve, reject) => {
                            const ret = fn.apply(null, [...args, (...a) => resolve(a)]);
                            ret && resolve(ret);
                        }
                    );
                };
            }

            /* 同步返回函数的Promise化 */
            //   const padd = promisify(add);
            //   padd(2, 3).then(
            //     (value) => console.log("value=", value) //5
            //   );

            const pmul = promisify(multiply);
            pmul(2, 3)
                .then((values) => {
                    console.log("value=", values);
                    return pmul(values[0], 4);
                })
                .then((values) => {
                    console.log("value=", values);
                    return pmul(values[0], 5);
                })
                .then((values) => console.log(values[0]));
        }
        // fn8();


        //19、 手撸数据驱动视图微框架

        (function () {
            /*
            <h3 id="hMyname">{myname}</h3>
            <p id="pMyname">{myname}</p>
            <h3 id="hMyage">{myage}</h3>
            <p id="pMyage">{myage}</p>
        */
            // let thrBox = document.createElement("div")
            // let pMyname = document.createElement("p")
            // let hMyage = document.createElement("h3")
            // let pMyage = document.createElement("p")
            // box.appendChild(thrBox)
            // thrBox.appendChild(pMyname)
            // thrBox.appendChild(hMyage)
            // thrBox.appendChild(pMyage)
            // function ffd(val) {
            //     var ood = "{}"
            //     console.log(ood)
            // }
            // ffd()
            // hMyname.innerText = "{myname}"
            // pMyname.innerText = "{myname}"
            // hMyage.innerText = "{myage}"
            // pMyage.innerText = "{myage}"
            function registerProperties(obj, properties) {
                properties.forEach(
                    p => {
                        console.log("p", p);
                        obj.propListeners = obj.propListeners || {}

                        obj.propListeners[p.name] = new Set()
                        p.listeners.forEach(
                            lis => obj.propListeners[p.name].add(lis)
                        )

                        Object.defineProperty(obj, p.name, {
                            get() {
                                console.log("getter");
                                return obj["stored_" + p.name]
                            },
                            set(newValue) {
                                console.log("setter", newValue);
                                obj["stored_" + p.name] = newValue

                                p.listeners.forEach(
                                    lis => {
                                        lis.innerText = newValue
                                        console.log(lis, "'s innerText has changed to",
                                            newValue);
                                    }
                                )
                            }
                        })

                    }
                )
            }

            const data = {}
            registerProperties(data, [{
                    name: "myname",
                    listeners: [hMyname, pMyname]
                },
                {
                    name: "myage",
                    listeners: [hMyage, pMyage]
                },
            ])

            data.myname = "黑哥"
            data.myage = 18

            setTimeout(() => {
                data.myname = "白鸽"
                // data.myage = 36
            }, 3000);

            setInterval(
                () => data.myage++,
                1000
            )
        })()

       //20、数组APIreduce

        const arr012 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        // 设置初始值为 0 
        const initialValue = 0
        // 以前值：previousValue  当前值：currentValue
        const getValue = arr012.reduce((previousValue, currentValue) => previousValue + currentValue, initialValue)
        console.log(getValue);

        // 数组的批处理API： forEach, filter, map, every, some, find, reduce
        /* 使用批处理函数实现如下功能 */

        // 遍历数组
        // 将所有元素映射为对应的平方数，打印映射出的新数组
        var arrMap = []
        var arrMap = arr012.map((v) => { 
            return v * v
         })
         console.log(arrMap)
        var arrMap = arr012.map(v => v * v)
         console.log(arrMap)

        // 过滤出3的倍数，打印过滤后的结果数组
        arr012.filter((v) => { v%3==0?console.log(v):"" })

        //判断arr中是否所有元素都是3的倍数
        arr012.every((v) => { v%3==0?console.log(true):console.log(false)})

        //判断arr中是否有元素都是3的倍数
        arr012.some((v) => { v%3==0?console.log(v , "满足条件为：" ,true):console.log(v , "不满足条件为：" , false)})

        // 从数组中找出第一个3的倍数
           let arrFind = arr012.find(v => v%3==0 )
           console.log(arrFind , "第一个倍数" )

        // 求arr中所有元素的和，使用reduce实现
        let arrReduce01 = arr012.reduce(( cur , total) => cur+total)
        console.log(arrReduce01, "累加结果")

        // 在100的基础上，加入arr中所有元素的和，使用reduce实现
        // cur初始值100   total导入的数据
        //// let arrReduce02 = arr012.reduce(( cur , total) =>  { return cur+total },100)
        //// console.log(arrReduce02, "累加结果")
        let arrReduce02 = arr012.reduce((accumulator, currentValue) => { 
            return accumulator + currentValue
        }, 100 )
        console.log(arrReduce02, "累加结果")


        // 五大正则表达式方法
        //返回str中是否包含reg定义的子串
        const bool = /\d+/.test("str");

        //返回执行匹配的结果[整体子串第一个括号匹配到的子串 第二个括号匹配到的子串...]
        const regArr = /\d+/.exec("str")

        //匹配:返回所有匹配到的子串形成的数组
        const subStrs = "str".match(/d+/g)

        //检索返回首个子串出现的下标
        const index = "str".search(reg)

        //替换:将所有匹配到的子串替换为根据函数
        const newStr = "str".replace(
            reg, //通常有全局模式
            //每个匹配到的子串执行一次回调返回替换的新子串
            function (subStr) {
                return "替换subStr的新子串"
            }
        )
    </script>

</body>

</html>